package org.rapc.controller;

import org.rapc.config.FileServiceConfiguration;
import org.rapc.service.AuthControllerService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("file")
public class FileController {
    @Resource
    private FileServiceConfiguration fileServiceConfiguration;

    @Resource
    private AuthControllerService authControllerService;

    @GetMapping("{id}")
    private ResponseEntity<String> file(@PathVariable String fileName, @RequestHeader Map<String, String> requestHeader) {
        if (fileName == "") {
            return  new ResponseEntity<>("404", HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();

        authControllerService.loadAuth(fileName, requestHeader, headers);

        fileServiceConfiguration.setContentDisposition(
                fileServiceConfiguration.getContentDisposition().replace("${fileName}",
                        fileName)
        );

        fileServiceConfiguration.setXAccelRedirect(
                fileServiceConfiguration.getXAccelRedirect().replace("${fileName}",
                        fileName)
        );

        headers.add("x-accel-redirect", fileServiceConfiguration.getCacheControl());
        headers.add("x-accel-limit-rate", fileServiceConfiguration.getXAccelLimitRate());
        headers.add("x-accel-buffering", fileServiceConfiguration.getXAccelBuffering());
        headers.add("x-accel-expires", fileServiceConfiguration.getXAccelExpires());
        headers.add("x-accel-charset", fileServiceConfiguration.getXAccelCharset());
        headers.add("content-type", fileServiceConfiguration.getContentType());
        headers.add("content-disposition", fileServiceConfiguration.getContentDisposition());
        headers.add("set-cookie", fileServiceConfiguration.getSetCookie());
        headers.add("cache-control", fileServiceConfiguration.getCacheControl());
        headers.add("expires", fileServiceConfiguration.getExpires());

        return new ResponseEntity<>("img", headers, HttpStatus.OK);
    }
}
